/**
 * Copyright (c) 2005-2011 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: HibernateDao.java,v 1.1 2011/07/26 06:13:04 linzx Exp $
 */
package com.newy.core.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;

import com.newy.core.util.AssertUtils;
import com.newy.core.util.LangUtils;
import com.newy.core.util.Page;
import com.newy.core.util.ReflectionUtils;


/**
 * 封装SpringSide扩展功能的Hibernat DAO泛型基类.
 * 扩展功能包括分页查询,按属性过滤条件列表查询.
 * <br/>代码来自springside。
 * 
 * @param <T> DAO操作的对象类型
 * @param <ID> 主键类型
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class HibernateDao<T, ID extends Serializable> extends SimpleHibernateDao<T, ID> {
	/**
	 * 通过子类的泛型定义取得对象类型Class.
	 * eg.
	 * public class UserDao extends HibernateDao<User, Long>{
	 * }
	 */
	public HibernateDao() {
		super();
	}

	public HibernateDao(Class<T> entityClass) {
		super(entityClass);
	}

	//-- 分页查询函数 --//

	/**
	 * 分页获取全部对象.
	 */
	public Page getAll(final Page page) {
		return findPage(page);
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page 分页参数. 注意不支持其中的orderBy参数.
	 * @param hql hql语句.
	 * @param values 数量可变的查询参数,按顺序绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数.
	 */
	public Page findPage(final Page page, final String hql, final Object... values) {
		AssertUtils.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		long totalCount = countResult(hql, values);
		page.setTotalItems(totalCount);

		setPageParameterToQuery(q, page);

		List result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page 分页参数. 注意不支持其中的orderBy参数.
	 * @param hql hql语句.
	 * @param values 命名参数,按名称绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数.
	 */
	public Page findPage(final Page page, final String hql, final Map<String, ?> values) {
		AssertUtils.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		long totalCount = countResult(hql, values);
		page.setTotalItems(totalCount);

		setPageParameterToQuery(q, page);

		List result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按Criteria分页查询.
	 * 
	 * @param page 分页参数.
	 * @param criterions 数量可变的Criterion.
	 * 
	 * @return 分页查询结果.附带结果列表及所有查询输入参数.
	 */
	public Page findPage(final Page page, final Criterion... criterions) {
		AssertUtils.notNull(page, "page不能为空");

		Criteria c = createCriteria(criterions);

		long totalCount = countCriteriaResult(c);
		page.setTotalItems(totalCount);

		setPageParameterToCriteria(c, page);

		List result = c.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 通过Example来进行分页查找，字符串可模糊查询，并支持多关键字
	 */
	public Page findPageByExample(Page page, T entity){
		return findPageByExample(page, entity, null, null);
	}

	/**
	 * 通过Example来进行分页查找，字符串可模糊查询，并支持多关键字
	 * @param page 分页对象
	 * @param entity 查询条件
	 * @param defaultOrderBy 默认排序字段名
	 * @param defaultOrderAsc 默认是否按升级排序
	 */
	public Page findPageByExample(Page page, T entity, String defaultOrderBy, Boolean defaultOrderAsc){
		if (entity != null){
			LangUtils.makeFieldsLike(entity);
		}
		if (!page.isOrderBySetted()){
			if (defaultOrderBy != null) page.setOrderBy(defaultOrderBy);
			if (defaultOrderAsc != null) page.setOrder(defaultOrderAsc ? "asc" : "desc");
		}
		return findPage(page, Example.create(entity).enableLike());
	}

	/**
	 * 设置分页参数到Query对象,辅助函数.
	 */
	protected Query setPageParameterToQuery(final Query q, final Page page) {
		AssertUtils.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

		q.setFirstResult(page.getOffset());
		q.setMaxResults(page.getPageSize());

		return q;
	}

	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 */
	protected Criteria setPageParameterToCriteria(final Criteria c, final Page page) {
		AssertUtils.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

		c.setFirstResult(page.getOffset());
		c.setMaxResults(page.getPageSize());

		if (page.isOrderBySetted()) {
			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(page.getOrder(), ',');

			AssertUtils.isTrue(orderByArray.length == orderArray.length, "分页多重排序参数中,排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (Page.ASC.equals(orderArray[i])) {
					c.addOrder(CnOrder.asc(orderByArray[i]));
				} else {
					c.addOrder(CnOrder.desc(orderByArray[i]));
				}
			}
		}
		return c;
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countResult(final String hql, final Object... values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
		}
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countResult(final String hql, final Map<String, ?> values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
		}
	}
	
	/**
	 * 获取符合条件的记录总数
	 */
	protected long countResult(Criterion... criterions){
		return countCriteriaResult(this.createCriteria(criterions));
	}

	private String prepareCountHql(String orgHql) {
		String fromHql = orgHql;
		//select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;
		return countHql;
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	protected long countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
			ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		// 执行Count查询
		Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
		long totalCount = (totalCountObject != null) ? totalCountObject : 0;

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		return totalCount;
	}
}
